package com.ruoyi.common.jwt;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Token;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    public static final String USER_KEY = "USER_ID";
    public static final String USER_INFO = "USER_INFO";

    private static final Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private JwtUtil tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //获取注解
        Token annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Token.class);
        } else {
            return true;
        }


        //没有声明需要权限,或者声明不验证权限
        if (annotation == null || annotation.validate() == false) {
            return true;
        }
        log.info("annotation {}", annotation);

//        token 获取用户信息
        LoginUser loginUser = tokenService.getLoginUser(request);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");


        //判断是否有token
        if (StringUtils.isNotNull(loginUser)) {
            //验证token 时效
            System.out.print("验证用的基本信息==token==>>：" + loginUser);
            boolean verify = JwtUtil.verify(loginUser.getToken(), loginUser.getUser().getLoginName(), loginUser.getUser().getPassword());
            System.out.println(verify);

            tokenService.verifyToken(loginUser);
//            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

//            request.setAttribute(USER_KEY, loginUser.getUser().getUserId());
        } else {
            try {
                writer = response.getWriter();
                AjaxResult error = AjaxResult.error("缺少token，拒绝访问");
                writer.println(JSONObject.toJSON(error));
                response.setStatus(500);
                log.info("缺少token，拒绝访问");
                return false;
            } catch (IOException e) {
                log.error("response error", e);
            } finally {
                if (writer != null)
                    writer.close();
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}

